package com.simple.datax.conn.impl;

import java.util.concurrent.atomic.AtomicInteger;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;

/** 
 * @Title: SendThreadPool.java 
 * @Package com.simple.datax.conn.impl 
 * @Description: SendThread 对象池. 主要目的是控制线程数量
 * @author Joe Jin 
 * @date 2013-1-10
 * @version V1.0 
 */
public class SendThreadPool {

	private static final Logger logger = LoggerFactory
			.getLogger(SendThreadPool.class);
	private AtomicInteger count = new AtomicInteger();
	private static final int MAX = 50;
	private static SendThreadPool instance;
	
	/**
	 * Singleton
	 * @return
	 */
	public synchronized static SendThreadPool getInstance() {
		if (instance == null) {
			instance = new SendThreadPool();
		}
		return instance;
	}
	
	/**
	 * 获取可以用对象
	 * @return 如果没有可用对象，返回null
	 * @throws Exception
	 */
	public synchronized SendThread borrowObject() throws Exception {
//		logger.debug(String.valueOf(count.get()));
//		System.out.println(String.valueOf(count.get()));
		if (count.get() >= MAX) {
			logger.debug("Send Thread reached maxnimum.");
			return null;
		} else {
			SendThread object = new SendThread(this);
			count.getAndIncrement();
			return object;
		}
	}

	/**
	 * 对象被还回
	 * @param obj
	 */
	public void returnObject(SendThread obj) {
		count.getAndDecrement();
//		logger.debug(String.valueOf(count.getAndDecrement()));
//		System.out.println(String.valueOf(count.getAndDecrement()));
	}
}
